<template>
	<view class="group-buy-container">
		<!-- 自定义导航栏 -->
		<view class="custom-navbar">
			<view class="navbar-left">
				<uni-icons type="left" size="20" @click="goBack"></uni-icons>
			</view>
			<view class="navbar-title">优惠团购</view>
			<view class="navbar-right">
				<uni-icons type="refresh" size="20" @click="refreshGroupBuy"></uni-icons>
				<uni-icons type="location" size="20" @click="showLocation" style="margin-left: 8px;"></uni-icons>
			</view>
		</view>
		
		<!-- 团购商品列表 -->
		<view class="group-buy-list">
			<!-- 加载状态 -->
			<view v-if="loading" class="loading-container">
				<uni-icons type="spinner-cycle" size="24" color="#007AFF"></uni-icons>
				<text class="loading-text">加载中...</text>
			</view>
			
			<view v-else-if="currentProducts.length === 0" class="empty-products">
				<uni-icons type="gift" size="48" color="#ccc"></uni-icons>
				<text class="empty-text">暂无团购商品</text>
			</view>
			
			<view 
				v-else
				class="product-item" 
				v-for="(product, index) in currentProducts" 
				:key="index"
				@click="goToProductDetail(product)"
			>
				<view class="product-image">
					<image :src="product.image" mode="aspectFill" class="product-img"></image>
				</view>
				<view class="product-info">
					<view class="product-title">{{ product.title }}</view>
					<view class="product-arrow">
						<uni-icons type="right" size="16" color="#007AFF"></uni-icons>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 加载更多 -->
		<view v-if="hasMore" class="load-more" @click="loadMoreProducts">
			<text class="load-more-text">加载更多</text>
		</view>
	</view>
</template>

<script>
	import uniIcons from '@dcloudio/uni-ui/lib/uni-icons/uni-icons.vue';
	import { groupPurchaseApi } from '@/api/index.js';
	
	export default {
		components: { 
			uniIcons
		},
		data() {
			return {
				currentCategory: 'all',
				categories: [
					{ key: 'all', name: '全部' },
					{ key: 'travel', name: '旅游' },
					{ key: 'food', name: '美食' },
					{ key: 'entertainment', name: '娱乐' },
					{ key: 'shopping', name: '购物' }
				],
				banners: [
					{ image: '/static/c1.png', title: '双十二大促销' },
					{ image: '/static/c2.png', title: '新用户专享' },
					{ image: '/static/c3.png', title: '限时团购' }
				],
				allProducts: [],
				hasMore: false,
				loading: false,
				useMockData: false
			};
		},
		computed: {
			currentProducts() {
				if (this.currentCategory === 'all') {
					return this.allProducts;
				}
				return this.allProducts.filter(product => product.category === this.currentCategory);
			}
		},
		async onLoad() {
			await this.initData();
		},
		onShow() {
			// 页面显示时刷新数据
			this.initData();
		},
		methods: {
			// 初始化数据
			async initData() {
				try {
					this.loading = true;
					
					console.log('开始获取团购数据...');
					
					// 使用新的API接口获取团购数据
					const result = await groupPurchaseApi.getActiveGroupPurchases();
					
					console.log('团购列表API返回结果:', result);
					console.log('result.code:', result.code);
					console.log('result.data:', result.data);
					console.log('result.msg:', result.msg);
					
					// 检查API响应
					if (result && result.code === 200 && result.data && result.data.length > 0) {
						// 使用后端数据
						this.allProducts = this.convertBackendData(result.data);
						this.useMockData = false;
						console.log('成功从后端获取团购数据，数量:', this.allProducts.length);
					} else {
						console.log('后端数据获取失败，响应详情:', {
							hasResult: !!result,
							code: result?.code,
							hasData: !!result?.data,
							dataLength: result?.data?.length
						});
						// 如果没有数据，显示空状态
						this.allProducts = [];
						this.useMockData = false;
					}
				} catch (error) {
					console.error('初始化数据失败:', error);
					this.allProducts = [];
					this.useMockData = false;
				} finally {
					this.loading = false;
				}
			},
			
			// 转换后端数据格式
			convertBackendData(backendData) {
				console.log('开始转换后端数据，原始数据:', backendData);
				
				const convertedData = backendData.map((product, index) => {
					// 根据后端数据字段进行转换
					const converted = {
						id: product.id || product.groupPurchaseId,
						category: this.mapCategory(product.title || product.content || ''),
						title: product.title || product.groupName || '团购活动',
						description: product.content || product.description || '暂无描述',
						currentPrice: (product.presentPrice || product.currentPrice || 0).toString(),
						originalPrice: (product.originalPrice || product.oldPrice || 0).toString(),
						groupCount: product.targetCount || product.groupCount || 10,
						salesCount: product.currentCount || product.salesCount || 0,
						image: product.img || product.image || '/static/c1.png',
						isHot: product.status === 1 || product.isHot === true,
						discount: this.calculateDiscount(product.originalPrice || 0, product.presentPrice || 0),
						endTime: product.endTime || product.expireTime,
						startTime: product.startTime || product.createTime
					};
					
					console.log(`第${index + 1}条数据转换:`, {
						原始: product,
						转换后: converted
					});
					
					return converted;
				});
				
				console.log('转换完成，最终数据:', convertedData);
				return convertedData;
			},
			
			// 映射分类
			mapCategory(title) {
				if (!title) return 'other';
				
				if (title.includes('旅游') || title.includes('景点') || title.includes('故宫')) return 'travel';
				if (title.includes('美食') || title.includes('餐厅') || title.includes('小吃')) return 'food';
				if (title.includes('娱乐') || title.includes('电影') || title.includes('游戏')) return 'entertainment';
				if (title.includes('购物') || title.includes('商品') || title.includes('优惠')) return 'shopping';
				
				return 'other';
			},
			
			// 计算折扣
			calculateDiscount(originalPrice, currentPrice) {
				if (!originalPrice || !currentPrice || originalPrice <= 0) return '0%';
				const discount = Math.round((1 - currentPrice / originalPrice) * 100);
				return discount > 0 ? `${discount}%` : '0%';
			},
			
			// 刷新团购
			async refreshGroupBuy() {
				await this.initData();
				uni.showToast({
					title: '刷新成功',
					icon: 'success'
				});
			},
			
			// 返回上一页
			goBack() {
				// 优惠团购页面直接返回到首页
				uni.navigateTo({
					url: '/pages/index/index'
				});
			},
			
			// 显示更多选项
			showMoreOptions() {
				uni.showActionSheet({
					itemList: ['分享', '收藏', '设置'],
					success: (res) => {
						if (res.tapIndex === 0) {
							uni.showToast({ title: '分享功能开发中', icon: 'none' });
						} else if (res.tapIndex === 1) {
							uni.showToast({ title: '收藏成功', icon: 'success' });
						} else if (res.tapIndex === 2) {
							uni.showToast({ title: '设置功能开发中', icon: 'none' });
						}
					}
				});
			},
			
			// 显示位置
			showLocation() {
				uni.showToast({
					title: '定位功能开发中',
					icon: 'none'
				});
			},
			
			// 切换分类
			switchCategory(categoryKey) {
				this.currentCategory = categoryKey;
			},
			
			// 跳转到商品详情
			goToProductDetail(product) {
				uni.navigateTo({
					url: `/pages/GroupBuy/GroupBuyDetail?productid=${product.id}`
				});
			},
			
			// 参与团购
			joinGroup(product) {
				uni.showModal({
					title: '确认参团',
					content: `确定要参与"${product.title}"的团购吗？`,
					success: (res) => {
						if (res.confirm) {
							uni.showToast({
								title: '参团成功',
								icon: 'success'
							});
						}
					}
				});
			},
			
			// 加载更多商品
			loadMoreProducts() {
				uni.showToast({
					title: '没有更多商品了',
					icon: 'none'
				});
				this.hasMore = false;
			}
		}
	}
</script>

<style lang="scss" scoped>
	.group-buy-container {
		background-color: #f5f5f5;
		min-height: 100vh;
	}
	
	// 自定义导航栏
	.custom-navbar {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 44px 16px 12px 16px;
		background-color: #ffffff;
		border-bottom: 1px solid #f0f0f0;
		
		.navbar-left {
			width: 40px;
		}
		
		.navbar-title {
			font-size: 18px;
			font-weight: bold;
			color: #333333;
		}
		
		.navbar-right {
			width: 40px;
			display: flex;
			justify-content: flex-end;
		}
	}
	

	
	// 团购商品列表
	.group-buy-list {
		padding: 16px;
		
		.loading-container {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			padding: 60px 20px;
			
			.loading-text {
				margin-top: 16px;
				font-size: 14px;
				color: #999999;
			}
		}
		
		.empty-products {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			padding: 60px 20px;
			
			.empty-text {
				margin-top: 16px;
				font-size: 14px;
				color: #999999;
			}
		}
		
		.product-item {
			background-color: #ffffff;
			margin-bottom: 16px;
			border-radius: 12px;
			overflow: hidden;
			box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
			
			.product-image {
				position: relative;
				height: 240px;
				
				.product-img {
					width: 100%;
					height: 100%;
				}
			}
			
			.product-info {
				padding: 16px;
				display: flex;
				justify-content: space-between;
				align-items: center;
				
				.product-title {
					font-size: 16px;
					font-weight: bold;
					color: #333333;
					flex: 1;
				}
				
				.product-arrow {
					margin-left: 12px;
				}
			}
		}
	}
	
	// 加载更多
	.load-more {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 16px;
		background-color: #ffffff;
		
		.load-more-text {
			font-size: 14px;
			color: #007AFF;
		}
	}
</style> 